#-*-coding:utf-8-*-
#!/usr/bin/python

from lib import config, req_sy, json_sy
from bs4 import BeautifulSoup
import codecs
import onliveDown
import time
import re

# 处理来源于火猫TV的直播视频，直播地址： http://www.huomaotv.com/live/907
def pro_onlivedata_from_huomao(zbid, f_url_ex, url_pre = 'http://www.huomaotv.com/live/'):
	url = config.HUOMAO_VIEW % zbid
	print u'huomao, ' + url
	html = req_sy.get_html(url, f_url_ex)
	time.sleep(0.2)
	if html.strip() != '':
		soup = BeautifulSoup(html, 'html.parser', from_encoding = 'utf-8')
		# 查找当前直播地址
		text = soup.find(text = re.compile("video_name"))
		matchObj = re.search(r'var\s+video_name.*\'(.*)\';', text)
		if matchObj:
			VideoIDS = matchObj.group(1)
			# src="http://swf.huomaotv.com/huomaoplayerv2.swf?ver=20150721&amp;initSize=big&amp;VideoIDS=Ct_FT9PPzbDNbR1cN10&amp;live_id=5325&amp;streamtype=live&amp;autostart=true&amp;url=http://www.huomaotv.com&amp;s=swf&amp;g=get_video_data&amp;hasDanmu=0&amp;hasFitPage=0&amp;hasLowBitrate=1&amp;hasFeedBack=0&amp;hasRefresh=1"
			return 'http://swf.huomaotv.com/huomaoplayerv2.swf?ver=20150721&amp;initSize=big&amp;VideoIDS=' + str(VideoIDS) + '&amp;live_id=' + str(zbid) + '&amp;streamtype=live&amp;autostart=true&amp;url=http://www.huomaotv.com&amp;s=swf&amp;g=get_video_data&amp;hasDanmu=0&amp;hasFitPage=0&amp;hasLowBitrate=1&amp;hasFeedBack=0&amp;hasRefresh=1'
		else:
			return ''

def huomao_insert_action(dbconn):
	onlive_src = 'huomao'
	game_type = config.HUOMAO_GAME
	file_name = onlive_src + '.log'
	file_err_name = onlive_src + '_err.log'
	file_url_ex = onlive_src + '_pagedown_err.log'
	f = codecs.open(file_name, 'w', 'utf8')
	f_err = codecs.open(file_err_name, 'a+', 'utf8')
	f_url_ex = codecs.open(file_url_ex, 'a+', 'utf8')
	# 火猫TV视频列表页api: http://www.huomaotv.com/channel/all?ajax=1&p=1
	page = 1
	# 在线人数作为是否继续爬取的判断条件
	top_views = 100
	while page < 2 and top_views > 30:
		top_views = 29
		cursor = dbconn.cursor()
		huomao_api = config.HUOMAO_API % page
		response = json_sy.request_ajax_url(huomao_api)
		if len(response) != 0:
			res_list = response
			for zb in res_list:
				 # 判断是否在直播
				is_live = zb['is_live']
				if is_live == '0':
					continue
				gameHostName = zb['gid']
				if gameHostName not in game_type:
					continue
				views = int(zb['views'])
				if top_views < views:
					top_views = views
				print str(page) + ', views:'+ str(views) + ',top_views:'+ str(top_views) + ',' + gameHostName +'\r\n'
				zbid = zb['id']
				livedata = pro_onlivedata_from_huomao(zbid,f_url_ex)
				zbname = zb['username']
				source = onlive_src
				title = zb['channel']
				category = game_type[gameHostName]
				inputtime = int(time.time())
				zb_thumb = zb['head_img'].replace('small','middle')
				thumb = 'http://www.huomaotv.com' + zb['img']
				try:
					cursor.execute("INSERT INTO `sy_video_onlive` (`zbid`, `zbname`, `source`, `title`, `views`, `category`, `isOnlive`, `inputtime`, `zb_thumb`, `thumb`, `livedata`) VALUES (%s, %s, %s, %s, %s, %s, 1, %s, %s, %s, %s)",(zbid, zbname, source, title, views, category, inputtime, zb_thumb, thumb, livedata))
				except Exception, e2:
					print Exception, e2
					print >> f_err, Exception, e2
				dbconn.commit()
		cursor.close()
		page = page + 1
	f.close()
	f_err.close()

if __name__ == "__main__":
	dbconn = onliveDown.getConnection()
	huomao_insert_action(dbconn)